/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[CaptchaGeneratorServlet.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package servlet.cases;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 生成验证码
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebServlet(name = "CaptchaGeneratorServlet", urlPatterns = "/captchaCode")
public class CaptchaGeneratorServlet extends HttpServlet {

	private static final long serialVersionUID = 1309284118818772154L;

	public static final String CAPTCHA_CODE_KEY = "CAPTCHA_CODE_KEY";

	// 设置验证图片的宽度, 高度, 验证码字符的个数
	private int width = 152;
	private int height = 40;
	private int codeCount = 6;

	// 验证码字体的高度
	private int fontHeight = 4;

	// 验证码中的单个字符基线. 即: 验证码中的单个字符位于验证码图形左上角的[codeX, codeY]位置处
	private int codeX = 0;
	private int codeY = 0;

	// 验证码由哪些字符组成
	char[] codeSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789".toCharArray();

	// 初始化验证码图形属性
	@Override
	public void init() {
		fontHeight = height - 2;
		codeX = width / (codeCount + 2);
		codeY = height - 4;
	}

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 定义一个类型为BufferedImage.TYPE_INT_RGB类型的图像缓存
		BufferedImage image = null;
		image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		// 在image中创建一个Graphics2D图像
		Graphics2D graphics = null;
		graphics = image.createGraphics();

		// 设置一个颜色, 使用Graphics2D对象的后续图形使用这个颜色
		graphics.setColor(Color.WHITE);

		// 填充一个指定的矩形:
		// x 要填充矩形的x坐标; y 要填充矩形的y坐标; width 要填充矩形的宽度; height 要填充矩形的高度
		graphics.fillRect(0, 0, width, height);

		// 创建一个Font对象: name字体名称; style Font的样式常量; size Font的点大小
		Font font = null;
		font = new Font("", Font.BOLD, fontHeight);
		// 使用Graphics2D对象的后续图形使用此字体
		graphics.setFont(font);

		graphics.setColor(Color.BLACK);

		// 绘制指定矩形的边框, 绘制出的矩形将比构件宽一个也高一个像素
		graphics.drawRect(0, 0, width - 1, height - 1);

		// 随机产生15条干扰线, 使图像中的认证码不易被其它程序探测到
		Random random = null;
		random = new Random();
		graphics.setColor(Color.GREEN);
		for (int i = 0; i < 15; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(20);
			int y1 = random.nextInt(20);
			graphics.drawLine(x, y, x + x1, y + y1);
		}

		// 创建captchaCode对象, 用于保存随机产生的验证码, 以便用户登录后进行验证
		StringBuffer captchaCode;
		captchaCode = new StringBuffer();

		for (int i = 0; i < codeCount; i++) {
			// 得到随机产生的验证码数字
			String tempCode = null;
			tempCode = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);

			// 把正在产生的随机字符放入到StringBuffer中
			captchaCode.append(tempCode);

			// 用随机产生的颜色将验证码绘制到图像中
			graphics.setColor(Color.BLUE);
			graphics.drawString(tempCode, (i + 1) * codeX, codeY);
		}

		// 把captchaCode放入到HttpSession中
		request.getSession().setAttribute(CAPTCHA_CODE_KEY, captchaCode.toString());

		// 禁止图像缓存
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		// 将图像输出到输出流中
		ServletOutputStream out = null;
		out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		out.close();
	}
}
